import { Component, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from '../../services/user.service';
import { User } from '../../entity/User';
import { Examination } from '../../entity/Examination';
import { ExamResult } from '../../entity/ExamResult';
import { Taoti } from '../../entity/Taoti';
import { NzMessageService } from 'ng-zorro-antd';
import { RepositionScrollStrategy } from '@angular/cdk/overlay';

@Component({
    selector: 'app-examination',
    templateUrl: './examination.component.html',
    styleUrls: ['./examination.component.css']
})
export class ExaminationComponent implements OnInit {
    user: User;
    min: number;
    totalMin: number;
    timeStr: string;
    examResult: ExamResult;
    userExam: Examination = new Examination(); // 用户数据库中问答
    userAnswer: Examination = new Examination(); // 用户新的回答
    taotiId: string;
    taoti: Taoti;
    minute: number;
    isShowAnswer = false;
    // 显示弹出框
    isVisible = false;

    success = 0;
    error = 0;

    private lastExamUrl = '/api/Exam/GetLastExam';
    private findTaotiUrl = '/api/TaoTi/findById';
    private nextExamUrl = '/api/Exam/GetNextExam';
    private prevExamUrl = '/api/Exam/GetPrevExam';
    private examUrl = '/api/Exam/findExamByStuIDAndqAndQuestionIDAndTaotiID';
    private examSaveUrl = '/api/Exam/insert';

    constructor(private route: ActivatedRoute
        , private http: HttpClient
        , private userService: UserService
        , private router: Router
        , private message: NzMessageService) {
        this.min = 60;
        this.totalMin = this.min * 60;
    }

    ngOnInit() {
        this.user = this.userService.getUser();

        this.route.params.subscribe((params) => {
            this.taotiId = params.id;

            this.http
                .get(`${this.findTaotiUrl}?id=${this.taotiId}`)
                .subscribe(response => {
                    this.taoti = response as Taoti;
                    if (this.taoti != null) {
                        this.minute = this.taoti.minute * 60;
                        setInterval(() => {
                            this.minute -= 1;
                            this.timeStr = `${(this.minute / 60 - 1).toFixed(0)}分${this.minute % 60}秒`;
                        }, 1000);
                    }
                });

            this.http
                .get(`${this.lastExamUrl}?stuId=${this.user.id}&taotaoId=${this.taotiId}`)
                .subscribe(response => {
                    this.examResult = response as ExamResult;
                });
        });
    }

    prev() {
        this.http
            .get(`${this.prevExamUrl}?taotaoId=${this.taotiId}&id=${this.examResult.data.id}&type=${this.examResult.questionType}`)
            .subscribe(response => {
                if (response != null) {
                    this.examResult = response as ExamResult;
                    this.findExam();
                } else {
                    this.message.error('没有上一题了');
                }
            });
    }

    showModal = () => {
        this.isVisible = true;
    }

    handleOk = (e) => {
        this.isVisible = false;
        this.router.navigate(['content/home']);
    }

    handleCancel = (e) => {
        this.isVisible = false;
    }

    next() {
        if (this.examResult.questionType == 'Programme') {
            this.validateProgram();
        } else {
            this._next();
        }
    }

    _next() {
        if (this.userExam.id == null && !this.validate()) {
            this.message.error('请作答');
            return false;
        }
        if (this.userExam.id == null && this.validate()) {
            this.submit();
        }
        this.isShowAnswer = true;
        setTimeout(_ => {
            this.isShowAnswer = false;
            this.userAnswer = new Examination();

            this.http
                .get(`${this.nextExamUrl}?taotaoId=${this.taotiId}&id=${this.examResult.data.id}&type=${this.examResult.questionType}`)
                .subscribe(response => {
                    if (response != null) {
                        this.examResult = response as ExamResult;
                        this.findExam();
                    } else {
                        this.http
                            .get(`/api/Exam/GetOnlyResult?stuid=${this.user.id}`)
                            .subscribe(res => {
                                this.success =  (<any>res)[0];
                                this.error =  (<any>res)[1];
                                this.showModal();
                            });
                    }
                });
        }, 3000);
    }

    findExam() {
        this.http
            .get(`${this.examUrl}?taotaoId=${this.taotiId}
            &stuID=${this.user.id}&questionID=${this.examResult.data.id}&type=${this.examResult.questionType}`)
            .subscribe(response => {
                if (response != null) {
                    this.userExam = response as Examination;
                } else {
                    this.userExam = new Examination();
                }
            });
    }

    // 作答了
    examEvent(value: Examination) {
        this.userAnswer = new Examination();
        if (value != null && value.answer1 != null) {
            this.userAnswer.answer1 = value.answer1;
        }
        if (value != null && value.answer2 != null) {
            this.userAnswer.answer2 = value.answer2;
        }
        if (value != null && value.answer3 != null) {
            this.userAnswer.answer3 = value.answer3;
        }
        if (value != null && value.answer4 != null) {
            this.userAnswer.answer4 = value.answer4;
        }
    }

    submit() {
        this.userAnswer.taotiID = <any>this.taotiId;
        this.userAnswer.stuID = this.user.id;
        this.userAnswer.questionID = <any>this.examResult.id;
        this.userAnswer.type = this.examResult.questionType;
        this.http
            .post(this.examSaveUrl, JSON.stringify(this.userAnswer), {
                headers: new HttpHeaders({
                    'Content-type': 'application/json'
                })
            })
            .subscribe(response => {
                if (!response as boolean) {
                    this.message.error('保存答案失败！');
                }
            });
    }

    validate() {
        let res = false;
        if (this.userAnswer.answer1 != null) {
            res = true;
        } else if (this.userAnswer.answer2 != null) {
            res = true;
        } else if (this.userAnswer.answer3 != null) {
            res = true;
        } else if (this.userAnswer.answer4 != null) {
            res = true;
        }
        console.log('validate:' + res);
        return res;
    }

    validateProgram() {
        this.http
            .post('/api/UploadFile/ValidateC', (this.userAnswer.answer1 == null ? this.userExam.answer1 : this.userAnswer.answer1), {
                headers: new HttpHeaders({
                    'Content-type': 'application/json'
                })
            })
            .subscribe(response => {
                this.message.info(`编译的结果为：${response}`);
                const res = response.toString() == this.examResult.data.answer;
                if (res) {
                    this._next();
                } else {
                    this.message.error(`答案错误，请重试`);
                }
            });
    }

    userAnswerLog() {
        console.log(this.userAnswer.answer1);
        console.log(this.userAnswer.answer2);
        console.log(this.userAnswer.answer3);
        console.log(this.userAnswer.answer4);
    }
}
